<template>
  <div class="nav" :class="[navMenuState ? 'navMenuState' : '']" data-v-7moor>
    <div class="icon" :style="styleObject" data-v-7moor :class="{oem_7moor:isNone}">
      <span v-show="navMenuState" class="nav-title ellipsis" :title="$t('login.cloudService')">{{$t('login.cloudService')}}</span>
      <span class="hide">{{ loadMenuNews }}</span>
    </div>
    <div class="nav-items">
        <div class="nav-items-top">
          <scroll-bar :isTopShow="isNone">
          <div v-for="(nav,index) in navs" :key="index">
            <nav-item
              v-if="nav.show && nav.id !== 'nav_config'"
              :nav-type="nav.icon"
              :no-badge="nav.noBadge"
              :tip-content="$t(nav.content)"
              :link="nav.link"
              :ic = "nav.ic"
              :navObj="nav"
              @changeRoute="changeMenu"
              @navClick="navClick">
            </nav-item>
          </div>
          <div v-for="(nav, index) in thirdNavs" :key="index">
            <nav-item
              v-if="nav.show && nav.id !== 'nav_config'"
              :nav-type="nav.icon"
              :no-badge="nav.noBadge"
              :tip-content="$t(nav.content)"
              :link="nav.link"
              :ic = "nav.ic"
              :navObj="nav"
              @changeRoute="changeMenu"
              @navClick="navClick">
            </nav-item>
          </div>
          <div v-for="(nav,index) in twoNavs" :key="index">
            <nav-item
              v-if="nav.show && nav.id !== 'nav_config'"
              :nav-type="nav.icon"
              :no-badge="nav.noBadge"
              :tip-content="$t(nav.content)"
              :link="nav.link"
              :ic = "nav.ic"
              :navObj="nav"
              @changeRoute="changeMenu"
              @navClick="navClick">
            </nav-item>
            <nav-item-setting
              v-if="nav.show && nav.id === 'nav_config'"
              :ic = "nav.ic"
              :tip-content="$t(nav.content)"
            ></nav-item-setting>
          </div>
          </scroll-bar>
        </div>
      </div>
  </div>
</template>
<script>
  import navItem from './NavItem.vue'
  import NavItemSetting from './NavItemSetting.vue'
  import { mapValues } from 'lodash'
  import { addZhuGeTrack } from '@/utils/addZhuGeTrack.js'
  import ScrollBar from '../../ui-modules/ScrollBar'
  import * as types from '../../../store/mutation-types'
  import {isHasMenu} from '@/utils/m7Utils'
  export default {
    name: 'navBar',
    components: {
      navItem,
      NavItemSetting,
      ScrollBar
    },
    data () {
      return {
        configLogo: false, // 是否配置logo
        hasCallRole: false,
        styleObject: {}, // 计算背景色
        thirdNavs: {},
        twoNavs: {
          market: {
            id: 'nav_marketing',
            show: false,
            icon: 'nav_marketing',
            content: 'public.market',
            link: '/index/market',
            noBadge: true,
            ic: 'icon-yingxiaozhenduan1',
            isClick: false
          },
          report: {
            id: 'nav_report',
            show: false,
            icon: 'nav-report',
            content: 'public.report',
            link: '/index/report',
            noBadge: true,
            ic: 'icon-baobiao1',
            isClick: false
          },
          xrobot: {
            id: 'nav_robot',
            show: false,
            icon: 'nav-report',
            content: 'public.xrobot',
            link: '/index/xrobot',
            noBadge: true,
            ic: 'icon-jiqirentouxiang',
            isClick: false
          },
          discover: {
            id: 'nav_bi_report',   //  权限
            show: false,
            icon: 'nav-discover',    //  class名 被选中时用
            content: 'public.discover',  //  模块名
            link: '/index/discover',
            noBadge: true,    //   小红点
            ic: 'icon-discover',   //   图标
            isClick: false
          },
          monitor: {
            id: 'nav_monitor',
            show: false,
            icon: 'nav-monitor',
            content: 'public.monitor',
            link: '/index/monitor',
            noBadge: true,
            ic: 'icon-jiankong1',
            isClick: false
          },
          monitorNew: {
            id: 'nav_new_monitor',
            show: false,
            icon: 'nav-monitor',
            content: 'public.newMonitor',
            link: '/index/monitorNew',
            noBadge: true,
            ic: 'icon-xinbanjiankong',
            isClick: false
          },
//          bireport: {
//            id: 'nav_bi_report',
//            show: false,
//            link: '',
//            icon: 'nav-bireport',
//            content: 'public.bireport',
//            ic: 'icon-BIpingtai1',
//            isClick: false
//          },
          questionnaire: {
            id: 'nav_questionnaire',
            show: false,
            icon: 'nav-questionnaire',
            content: 'public.questionnaire',
            link: '/index/questionnaire',
            noBadge: true,
            ic: 'icon-wenjuantiaocha1',
            isClick: false
          },
          qualityCheck: {
            id: 'nav_qualityCheck',
            show: false,
            icon: 'nav-qualityCheck',
            content: 'public.qualityCheck',
            link: '/index/qualityCheck',
            noBadge: true,
            ic: 'icon-zhijian',
            isClick: false
          },
          intelligentQualityCheck: {
            id: 'nav_autoqc',
            show: false,
            icon: 'nav_autoqc',
            content: 'public.autoQc',
            link: '/index/intelligentQualityCheck',
            noBadge: true,
            ic: 'icon-zhinengzhijian',
            isClick: false
          },
//          misscall: {
//            id: 'my_call_sheet_leak',
//            show: false,
//            icon: 'nav-misscall',
//            content: 'public.misscall',
//            link: '/index/misscall',
//            noBadge: true,
//            ic: 'icon-weijielaidian'
//          },
          sms: {
            id: 'nav_sms',
            show: false,
            icon: 'nav-sms',
            content: 'public.SMS',
            link: '/index/sms',
            noBadge: true,
            ic: 'icon-duanxin2',
            isClick: false
          },
          urlInterface: {
            id: 'nav_url_interface',
            show: false,
            icon: 'nav-interface',
            content: 'public.interface',
            link: '/index/interface',
            noBadge: true,
            ic: 'icon-shouyeduijie',
            isClick: false
          },
          config: {
            id: 'nav_config',
            show: false,
            icon: 'nav-config',
            content: 'public.config',
            link: '/index/config',
            noBadge: true,
            ic: 'icon-shezhi',
            isClick: false
          },
          newConfig: {
            id: 'simple_config',
            show: false,
            icon: 'nav-config',
            content: 'public.config',
            link: '/index/newConfig',
            noBadge: true,
            ic: 'icon-shezhi',
            isClick: false
          }
        },
        navs: {
          workbench: {
            show: true,
            icon: 'nav-workbench',
            content: 'public.workbench',
            link: '/index/workbench',
            noBadge: true,
            ic: 'icon-gongzuotai1',
            isClick: false
          },
          cdr: {
            id: 'nav_call',
            show: false,
            icon: 'nav-cdr',
            content: 'public.call',
            link: '/index/call/cdr_call',
            noBadge: true,
            ic: 'icon-tonghua',
            isClick: false
          },
          im: {
            id: 'nav_webchat',
            show: false,
            icon: 'nav-im',
            content: 'public.webchat',
            link: '/index/webchat/webchat_todo',
            noBadge: true,
            ic: 'icon-zaixianzixun1',
            isClick: false
          },
          mail: {
            id: 'nav_email',
            show: false,
            icon: 'nav-mail',
            content: 'public.mail',
            link: '/index/email',
            noBadge: true,
            ic: 'icon-youjian1',
            isClick: false
          },
          customer: {
            id: 'nav_customer',
            show: false,
            icon: 'nav-customer',
            content: 'public.customer',
            link: '/index/customer',
            noBadge: true,
            ic: 'icon-kehu1',
            isClick: false
          },
          bussiness: {
            id: 'nav_business',
            show: false,
            icon: 'nav-bussiness',
            content: 'public.business',
            link: '/index/business',
            noBadge: true,
            ic: 'icon-gongdan1',
            isClick: false
          },
          km: {
            id: 'nav_km',
            show: false,
            icon: 'nav-km',
            content: 'public.km',
            link: '/index/km',
            noBadge: true,
            ic: 'icon-zhishiku1',
            isClick: false
          }
        }
      }
    },
    computed: {
      isNone () {
        return this.$store.state.oemObj.oemFlag && !this.configLogo
      },
      getCallScreen () {
        return this.$store.state.call.transCache.callScreen || ''
      },
      loadMenuNews () {
        if (this.$store.state.webchat.todoNum > 0 || this.$store.state.webchat.queueNum > 0) {
          this.navs.im.noBadge = false
        } else {
          this.navs.im.noBadge = true
        }
        if (this.$store.state.email.todoNum > 0 || this.$store.state.email.queueNum > 0) {
          this.navs.mail.noBadge = false
        } else {
          this.navs.mail.noBadge = true
        }
        let roleNum = this.$store.state.business.roleNum
        let total = this.$store.state.business.total
        if (total > 0 || roleNum > 0) {
          this.navs.bussiness.noBadge = false
        } else {
          this.navs.bussiness.noBadge = true
        }
        let cdrCallNum = this.$store.state.call.unReadCdr
        if (cdrCallNum && cdrCallNum > 0) {
          this.navs.cdr.noBadge = false
        } else {
          this.navs.cdr.noBadge = true
        }
      },
      navMenuState () {
        return this.$store.state.navMenuState || false
      }
    },
    watch: {
      getCallScreen (curr) {
        if (curr && this.hasCallRole) { // 有通话模块的权限
          this.$router.push({path: `/index/call/cdr_outbound/${curr}/outbound`, query: {flag: 'notify'}})
          this.$store.commit('call/REFRESH_CUST_RIGHT', Math.random())
        }
      },
      $route (to, from) {
        let session = window.sessionStorage
        let fromArr = from.path.split('/')
        let toArr = to.path.split('/')
        let data = {}
        data.url = from.path
        data.flag = false // 其他模块为false
        if ((fromArr[2] === 'config' && fromArr[3]) || (fromArr[2] === 'newConfig' && fromArr[3])) {  // 新设置记住上一次历史地址
          let fromItem = 'config'
          session.setItem(fromItem, JSON.stringify(data))
        }
        if (toArr[2] && toArr[2] !== 'webchat' && toArr[2] !== 'cdr_call') {
          this.$store.commit('BLANK', '')
        }
        if (toArr[2] && toArr[2] === 'webchat') {
          this.navs.im.link = to.path
          this.$store.commit('BLANK', toArr[3])
        }
        if (toArr[2] && toArr[2] === 'call') {
          this.navs.cdr.link = to.path
          this.$store.commit('BLANK', toArr[3])
        }
        this.handleGioEvent(to, from)
      }
    },
    methods: {
      handleGioEvent (to, from) {
        let fromArr = []
        if (from === 'beforeMount') {
          fromArr = ['', '']
        } else {
          fromArr = from.path.split('/')
        }
        let toArr = to.path.split('/')
        if (toArr[2] !== fromArr[2]) { // 说明是跨模块
          const obj = this.handleMenuName(toArr[2])
          if (obj) { // 有匹配到才埋点
            addZhuGeTrack(to.path)
            // gio('track', 'firstMenuClick', { 'functionName_var': obj.name, 'position_var': obj.index + '' })
          }
        }
      },
      handleMenuName (key) {
        let obj = null
        const navObj = { workbench: '云客服 - 工作台', call: '云客服 - 通话', webchat: '云客服 - 在线咨询', email: '云客服 - 邮件', customer: '云客服 - 客户', business: '云客服 - 工单', km: '云客服 - 知识库', applications: '云客服 - mopower应用', report: '云客服 - 报表', xrobot: '云客服 - 机器人', discover: '云客服 - Discover', monitor: '云客服 - 老版监控', monitorNew: '云客服 - 新版监控', questionnaire: '云客服 - 问券调查', qualityCheck: '云客服 - 质检', intelligentQualityCheck: '云客服 - 智能质检', sms: '云客服 - 短信', interface: '云客服 - 首页对接', config: '云客服 - 设置' }
        Object.keys(navObj).forEach((item, index) => {
          if (key === item) { // position_var 取的index, 后面菜单顺序做了调整，对应的navObj里顺序也要做变更
            obj = { name: navObj[item], index: index + 1 }
          }
        })
        return obj
      },
      changeMenu (navType) {
        this.$emit('changeMenu', navType)
      },
      navClick (data) {
        data.nav.isClick = data.status
        let obj = {...this.navs, ...this.thirdNavs, ...this.twoNavs}
        for (let item in obj) {
          if (data.nav.icon === item.icon) {
            item = data.nav
          }
          break
        }
        // 判断是否是点击机器人 进行百度统计
        if (data.nav.id === 'nav_robot') {
          window._hmt && window._hmt.push(['_trackEvent', '机器人', 'PM-引导页浏览'])
        }
      },
      isHaveMenu(func) {
        let user = this.$store.state.session.user
        return isHasMenu(func, user)
      },
    },
    beforeMount () {
      this.$store.commit('SET_CTI_UI_DESC')
      // 渲染logo和标签页ico
      this.$store.dispatch('getCache', { type: 'customLogo' }).then(res => {
        if (res[0].navigationLogo) {
          this.configLogo = true
          this.styleObject = {
            background: `url(${res[0].navigationLogo}) no-repeat`,
            backgroundSize: '1.7em auto',
            backgroundPosition: '18px',
            backgroundColor: '#202736'
          }
        }
        if (res[0].tabLogo) {
          var link = document.querySelector("link[rel*='icon']") || document.createElement('link')
          link.type = 'image/x-icon'
          link.rel = 'shortcut icon'
          link.href = res[0].tabLogo
          document.getElementsByTagName('head')[0].appendChild(link)
        }
      })
      let p1 = this.$store.dispatch('getApplications', {category: 'app'})
      let p2 = this.$store.dispatch('initMenu')
      Promise.all([p1, p2]).then(([res]) => {
        let menus = this.$store.state.session.clientMenu
        if (res && res.data) {
          let appTab = res.data
          let newAppTab = []
          if (appTab.length > 0) {
            appTab.forEach((item, index) => {
              this.thirdNavs[item._id] = {icon: item._id, noBadge: true, content: item.name, id: item._id, show: true, link: '/index/applications?' + item._id, url: item.url, ic: item.icon, thirdApp: true, navObj: item}
            })
          }
          this.$store.commit(types.SET_THIRDAPP, this.thirdNavs)
        }
        let index = 0
        let obj = {...this.navs, ...this.twoNavs}
        menus.forEach((menu, menuIndex) => {
          if (menu.id === 'nav_km') {
            index = menuIndex
          }
          mapValues(obj, nav => {
            if (nav.id === menu.id) {
              nav.show = true
            }
            if (menu.id === 'nav_call') { // 有通话模块的权限
              this.hasCallRole = true
            }
          })
        })
        // 知识库权限---没有知识库权限有快捷回复权限
        if (!menus.some(item => item.id === 'nav_km') && this.isHaveMenu('simple_public_quick_reply_config')) {
          this.navs.km.show = true
        }
        // newAppTab.unshift(index, 0)
        // Array.prototype.splice.apply(menus, newAppTab)
        // if (nav.id === 'nav_robot' && (this.$store.state.session.user.type === 'manager' || this.$store.state.session.user.type === 'admin')) { // 有管理员的权限
        //   nav.show = true
        // }
// //        如果是oem  隐藏掉 discover菜单
//         let oemFlag = this.$store.state.oemObj.oemFlag
//         if (oemFlag) {
//           this.navs.discover.show = false
//         }
        // 单点登录
        let tokenModule = this.$store.state.session.tokenModule
        if (tokenModule) {
          if (tokenModule === 'my_call_sheet_leak') {
            this.$router.push({path: '/index/call/cdr_pending', query: {pending: 'leakAssignMsg'}})
          } else {
            let link = null
            for (let i in obj) {
              let item = obj[i]
              if (item.id === ('nav_' + tokenModule) && item.show) {
                link = item.link
              }
            }
            if (link) {
              this.$router.push({path: link})
            } else {
              this.$router.push({path: '/index/workbench'})
            }
          }
        }
      })
      this.$store.dispatch('refreshUndealNum')
      this.$store.dispatch('getUndealInvitation')
      this.handleGioEvent(this.$route, 'beforeMount')
      // this.$store.dispatch('getCache', {type: 'guidance', loadFromServer: true})
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl'
  @media screen and (max-height: 650px)
    .nav
      font-size 12px
  .nav
    position absolute
    left 0
    top 0
    width 56px
    height 100%
    /*background #3a404c*/
    /*background #1f282c*/
    background #202736
    /*background -webkit-linear-gradient(top, $c-nav-to 0%, #0068a5 100%)*/
  .nav.navMenuState
    width 120px
  .icon
    /*box-size(1.85em,2.07em)*/
    background url(../../../assets/logo@4X.png) no-repeat
    background-size 1.7em auto
    background-position 18px 16px
    width 100%
    height 60px
    background-color #202736
    position relative
    z-index 10
    position relative
    .nav-title
      font-family: PingFang SC;
      font-weight: 500;
      color: #FFFFFF;
      font-size 16px
      position absolute
      top 16px
      left 45px
      width 60px
  .nav-items-top
    width 100%
    height calc(100vh - 60px)
    overflow-y scroll
    overflow-x hidden
  .nav-items-bottom
    bottom 0
    border-top 1px solid #0085ae
  ::-webkit-scrollbar-track-piece
    background-color transparent
    -webkit-border-radius 0
  ::-webkit-scrollbar-thumb
    background-color transparent
    border 0
    border-radius 0
  ::-webkit-scrollbar
    width 0
    height 0
</style>
